import React, { useEffect, useState, useRef } from "react";
import { useParams } from "react-router-dom";
import { Input, Button, message, List, Avatar } from "antd";
import {
  UserOutlined,
  CustomerServiceOutlined,
  SendOutlined,
} from "@ant-design/icons";
import { fetchChatHistory, sendMessage } from "../../../api/customerService";
import { useSelector } from "react-redux";

const CustomerServiceChat = () => {
  const { conversationId } = useParams();
  const adminId = useSelector((state) => {
    return state.user.userId;
  });
  const adminUsername = useSelector((state) => {
    return state.user.userName;
  });
  const [chatHistory, setChatHistory] = useState([]);
  const [inputMessage, setInputMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const chatEndRef = useRef(null);
  const wsRef = useRef(null);

  useEffect(() => {
    loadChatHistory();
    connectWebSocket();
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, [conversationId]);

  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [chatHistory]);

  const connectWebSocket = () => {
    const wsUrl = `ws://jevon-blog-api.com:3000/ws?userId=${adminId}&isAdmin=true`;
    wsRef.current = new WebSocket(wsUrl);

    wsRef.current.onopen = () => {
      console.log("WebSocket连接已建立");
      // message.success("WebSocket连接成功");
    };

    wsRef.current.onmessage = (event) => {
      console.log("接收消息", event.data);
      const newMessage = JSON.parse(event.data);
      if (newMessage.conversationId === conversationId) {
        setChatHistory((prev) => [...prev, newMessage]);
      }
    };

    wsRef.current.onerror = (error) => {
      console.error("WebSocket错误:", error);
      message.error("WebSocket连接错误");
    };

    wsRef.current.onclose = () => {
      console.log("WebSocket连接已关闭");
      // message.warning("WebSocket连接已关闭");
    };
  };

  const loadChatHistory = async () => {
    setLoading(true);
    try {
      const response = await fetchChatHistory(conversationId);
      if (response.code === 0 && Array.isArray(response.data)) {
        setChatHistory(response.data);
      } else {
        throw new Error("Invalid response data");
      }
    } catch (error) {
      console.error("获取聊天历史失败:", error);
      message.error("获取聊天历史失败: " + (error.message || "未知错误"));
    } finally {
      setLoading(false);
    }
  };

  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;

    try {
      const adminId = localStorage.getItem("userId") || "defaultAdminId";
      const response = await sendMessage(conversationId, inputMessage);
      if (response.code !== 0) {
        throw new Error(response.message || "发送消息失败");
      }

      const newMessage = {
        id: response.data.messageId,
        conversationId: conversationId,
        senderId: adminId,
        receiverId: response.data.receiver,
        content: inputMessage,
        timestamp: new Date().toISOString(),
        senderRole: "ADMIN",
        receiverRole: "USER",
        senderNickName: adminUsername,
      };

      setChatHistory((prev) => [...prev, newMessage]);
      setInputMessage("");
    } catch (error) {
      console.error("发送消息失败:", error);
      message.error("发送消息失败: " + (error.message || "未知错误"));
    }
  };

  const renderChatItem = (item) => (
    <List.Item key={item.id}>
      <List.Item.Meta
        avatar={
          <Avatar
            style={{
              backgroundColor:
                item.senderRole === "USER" ? "#87d068" : "#1890ff",
            }}
            icon={
              item.senderRole === "USER" ? (
                <UserOutlined />
              ) : (
                <CustomerServiceOutlined />
              )
            }
          />
        }
        title={
          item.senderRole === "USER"
            ? `用户(${item.senderNickName})`
            : `客服(${item.senderNickName})`
        }
        description={
          <div>
            <div>{item.content}</div>
            <small style={{ color: "#888" }}>
              {new Date(item.timestamp).toLocaleString()}
            </small>
          </div>
        }
      />
    </List.Item>
  );

  return (
    <div
      style={{
        height: "88vh",
        display: "flex",
        flexDirection: "column",
        maxWidth: "100%",
        margin: "0 auto",
      }}
    >
      {/* 聊天历史列表 */}
      <div
        style={{
          height: "95vh",
          overflowY: "scroll", // 允许滚动
          padding: "16px",
          marginBottom: "20px",
          // 隐藏滚动条
          scrollbarWidth: "none" /* Firefox */,
          "-ms-overflow-style": "none" /* IE and Edge */,
        }}
        className="hide-scrollbar" // 可以用类名来控制
      >
        <style>
          {`
            .hide-scrollbar::-webkit-scrollbar {
              display: none; /* Safari 和 Chrome */
            }
          `}
        </style>
        <List
          loading={loading}
          dataSource={chatHistory}
          renderItem={renderChatItem}
        />
        <div ref={chatEndRef} />
      </div>

      {/* 消息输入区域 */}
      <div
        style={{
          display: "flex",
          padding: "10px",
          borderTop: "1px solid #e8e8e8",
          background: "white",
        }}
      >
        <Input
          value={inputMessage}
          onChange={(e) => setInputMessage(e.target.value)}
          onPressEnter={handleSendMessage}
          placeholder="输入消息..."
          style={{ marginRight: "20px" }} // 输入框和按钮之间的间距
        />
        <Button
          onClick={handleSendMessage}
          type="primary"
          icon={<SendOutlined />}
        >
          发送
        </Button>
      </div>
    </div>
  );
};

export default CustomerServiceChat;
